package auth

import (
	"gin-demo/core"
	"net/http"

	"github.com/gin-gonic/gin"
)

// UserController 用户控制器
type UserController struct {
	service UserService
}

// Register godoc
// @Summary 新增用户/用户注册
// @Description 提交JSON数据新增用户账户
// @Tags Account
// @Accept  json
// @Produce  json
// @Param UserCreateForm body UserCreateForm true "创建用户"
// @Success 200 {object} User
// @Failure 400 {object} httputil.HTTPError
// @Failure 401 {object} httputil.HTTPError
// @Failure 403 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /auth/register [post]
func (c UserController) Register(ctx *gin.Context) {
	var createForm UserCreateForm
	if err := ctx.ShouldBindJSON(&createForm); err != nil {
		ctx.JSON(http.StatusBadRequest, err)
	} else {
		if user, err := c.service.Create(createForm); err != nil {
			ctx.JSON(http.StatusInternalServerError, err)
		} else {
			ctx.JSON(http.StatusOK, user)
		}
	}
}

// ChangePassword godoc
// @Summary 修改用户密码
// @Description 提交JSON数据修改制定用户密码
// @Tags Account
// @Accept  json
// @Produce  json
// @Param id path int true "User ID"
// @Param UserChangePasswordForm body UserChangePasswordForm true "修改密码"
// @Success 200 {object} User
// @Failure 400 {object} httputil.HTTPError
// @Failure 401 {object} httputil.HTTPError
// @Failure 403 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /auth/change_password/{id} [patch]
func (c UserController) ChangePassword(ctx *gin.Context) {
	if user, ok := c.service.GetByID(ctx.Param("id")); !ok {
		ctx.JSON(http.StatusNotFound, gin.H{"msg": "页面不存在！"})
	} else {
		var passwordForm UserChangePasswordForm
		if err := ctx.ShouldBindJSON(&passwordForm); err != nil {
			ctx.JSON(http.StatusBadRequest, err)
		} else {
			if err := c.service.Update(&user, gin.H{"password": passwordForm.Password}); err != nil {
				ctx.JSON(http.StatusInternalServerError, err)
			} else {
				ctx.JSON(http.StatusOK, user)
			}
		}
	}
}

// List godoc
// @Summary 查询用户列表
// @Description get users
// @Tags User
// @Accept  json
// @Produce  json
// @Param query query string false "username search by query" Format(email)
// @Success 200 {object} User
// @Failure 400 {object} httputil.HTTPError
// @Failure 401 {object} httputil.HTTPError
// @Failure 403 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /user/users [get]
func (c UserController) List(ctx *gin.Context) {
	query := ctx.Param("query")
	var paginator core.Paginator
	if err := ctx.ShouldBindQuery(paginator); err != nil {
		ctx.JSON(http.StatusBadRequest, err)
	} else {
		var users []User
		if err := paginator.Paging(c.service.QuerySet(query), &users); err != nil {
			ctx.JSON(http.StatusInternalServerError, err)
		} else {
			ctx.JSON(http.StatusOK, paginator)
		}
	}
}
